<template>
  <div>
    <router-view>
      <div v-if="stated">
        <div style="display: flex; align-items: center; justify-content: space-between">
          <el-button type="primary" @click="exportExcel">导出</el-button>
        </div>
        <div style="height: 2vh"></div>
        <el-card class="box-card">
          <template #header>
            <div style="font-size: 20px; font-weight: 600">
              <span>门诊订单</span>
            </div>
            <div style="height: 2vh"></div>
            <div style="display: flex; align-items: center">
              <div class="block">
                最后缴费时间：
                <el-date-picker
                  v-model="value1"
                  type="daterange"
                  range-separator="To"
                  start-placeholder="开始日期"
                  end-placeholder="结束日期"
                  :size="size"
                  @change="sarend"
                />
              </div>
              <div style="width: 15px"></div>
              <el-select
                v-model="value"
                class="m-2"
                filterable
                placeholder="科室选择"
                @change="kssearch"
                clearable
              >
                <el-option
                  v-for="item in options"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>
              <div style="width: 15px"></div>
              <div style="display: flex; align-items: center">
                <el-input
                  v-model="input"
                  placeholder="输入医生名称"
                  clearable
                  style="width: 250px"
                  @input="docsearch"
                />
                <div style="width: 8px"></div>
              </div>
              <div style="display: flex; align-items: center">
                <el-input
                  v-model="huanz"
                  placeholder="输入患者名称"
                  clearable
                  style="width: 250px"
                  @input="hzsearch"
                />
                <div style="width: 8px"></div>
              </div>
              <!-- <el-button type="primary" :icon="Search" @click="searchfilter">搜索</el-button> -->
            </div>
          </template>
          <div>
            <el-table
              ref="multipleTableRef"
              style="width: 100%"
              stripe
              :data="tableData.slice((currentPage4 - 1) * pageSize4, currentPage4 * pageSize4)"
              v-loading="loading"
              @selection-change="handleSelectionChange"
              max-height="60vh"
            >
              <el-table-column type="selection" width="55" />
              <el-table-column label="序号" property="id" width="60" align="center" fixed />
              <el-table-column
                label="待诊人"
                property="user.nickname"
                width="120"
                align="center"
                fixed
              />
              <el-table-column property="card" label="就诊卡号" width="180" align="center" />
              <el-table-column
                property="user.tel"
                label="手机号"
                show-overflow-tooltip
                width="140"
                align="center"
              />
              <el-table-column
                property="depart.name"
                label="挂号科室"
                show-overflow-tooltip
                width="140"
                align="center"
              />
              <el-table-column
                property="doctor_name"
                label="医生名称"
                show-overflow-tooltip
                width="120"
                align="center"
              />
              <el-table-column
                property="money"
                label="支付金额"
                show-overflow-tooltip
                width="120"
                align="center"
              />
              <el-table-column label="缴费状态" show-overflow-tooltip width="140" align="center">
                <template #default="scope">
                  <span v-if="scope.row.status === 1" style="color: rgb(43, 207, 43)"
                    ><el-tag class="ml-2" type="success">已支付</el-tag></span
                  >
                  <span v-else-if="scope.row.status === 2" style="color: red"
                    ><el-tag class="ml-2" type="danger">未支付</el-tag></span
                  >
                </template>
              </el-table-column>
              <el-table-column label="就诊状态" show-overflow-tooltip width="140" align="center">
                <template #default="scope">
                  <span v-if="scope.row.visit_status === 1" style="color: rgb(43, 207, 43)"
                    ><el-tag class="ml-2" type="danger">就诊完成</el-tag></span
                  >
                  <span v-else-if="scope.row.visit_status === 2" style="color: red"
                    ><el-tag class="ml-2" type="success">就诊中</el-tag></span
                  >
                </template>
              </el-table-column>
              <!-- <el-table-column property="name" label="缴费类型" show-overflow-tooltip width="140" align="center">
                <template #default="scope">微信支付</template>
              </el-table-column> -->
              <el-table-column
                property="order_code"
                label="订单号"
                show-overflow-tooltip
                width="140"
                align="center"
              />
              <el-table-column
                property="create_time"
                label="创建时间"
                show-overflow-tooltip
                width="150"
                align="center"
              />
              <el-table-column
                property="yes_time"
                label="最后缴费时间"
                show-overflow-tooltip
                width="180"
                align="center"
              />
              <el-table-column fixed="right" label="操作" align="center">
                <template #default="scope">
                  <el-button
                    type="primary"
                    plain
                    size="small"
                    @click="targets(scope.row.id, scope.row)"
                    >详情</el-button
                  >
                </template>
              </el-table-column>
            </el-table>
            <div style="height: 1vh"></div>
            <div style="display: flex; justify-content: center">
              <el-pagination
                v-model:current-page="currentPage4"
                v-model:page-size="pageSize4"
                :page-sizes="[10, 20, 50, 100]"
                :small="small"
                :disabled="disabled"
                :background="background"
                layout="total, sizes, prev, pager, next, jumper"
                :total="tableData.length"
              />
            </div>
          </div>
        </el-card>
      </div>
      <div v-if="defaults">
        <div style="display: flex; align-items: center; justify-content: space-between">
          <div class="top_navigate">
            <el-button type="primary" :icon="ArrowLeftBold" @click="returned">返回</el-button>
          </div>
          <div>&nbsp;</div>
        </div>
        <div style="height: 2vh"></div>
        <el-card class="box-card">
          <template #header>
            <div class="card-header">
              <span>患者信息</span>
            </div>
          </template>
          <div v-if="outpatientxq">
            <div class="arrow">
              <div class="user_inp">
                <div style="width: 120px; color: #afafaf">患者姓名</div>
                <div>{{ outpatientxq.user.nickname }}</div>
              </div>
              <div class="user_inp">
                <div style="width: 120px; color: #afafaf">医生姓名</div>
                <div>{{ outpatientxq.doctor_name }}</div>
              </div>
              <div class="user_inp">
                <div style="width: 120px; color: #afafaf">账户头像</div>
                <!-- <div>
                <img :src="outpatientxq.user.avatar" alt="" style="width: 75px; height: 75px; border-radius: 180%;"
                  @click="previewImage">
                <div v-if="showPreview" class="preview-container" @click="closePreview">
                  <img :src="outpatientxq.user.avatar" alt="" class="preview-image">
                </div>
              </div> -->
                <el-image
                  :src="outpatientxq.user.avatar"
                  :zoom-rate="1.2"
                  :max-scale="7"
                  :min-scale="0.2"
                  :preview-src-list="[outpatientxq.user.avatar]"
                  fit="cover"
                  preview-teleported="true"
                  style="width: 75px; height: 75px; border-radius: 180%"
                />
              </div>
            </div>
            <div class="arrow">
              <div class="user_inp">
                <div style="width: 120px; color: #afafaf">证件类型</div>
                <div>身份证</div>
              </div>
              <div class="user_inp">
                <div style="width: 120px; color: #afafaf">证件号码</div>
                <div>{{ outpatientxq.user.code }}</div>
              </div>
              <div class="user_inp" style="visibility: hidden">
                <div style="width: 120px; color: #afafaf">患者头像</div>
                <div>张三</div>
              </div>
            </div>
            <div class="arrow">
              <div class="user_inp">
                <div style="width: 120px; color: #afafaf">就诊人地址</div>
                <div>{{ outpatientxq.user.address }}</div>
              </div>
              <div class="user_inp">
                <div style="width: 120px; color: #afafaf">手机号</div>
                <div>{{ outpatientxq.user.tel }}</div>
              </div>
              <div class="user_inp">
                <div style="width: 120px; color: #afafaf">关系</div>
                <div>{{ outpatientxq.user.relationship }}</div>
              </div>
            </div>
            <div class="arrow">
              <div class="user_inp">
                <div style="width: 120px; color: #afafaf">性别</div>
                <div v-if="outpatientxq.user.sex == 1">男</div>
                <div v-else-if="outpatientxq.user.sex == 2">女</div>
              </div>
              <div class="user_inp">
                <div style="width: 120px; color: #afafaf">就诊时间</div>
                <div>{{ outpatientxq.create_time }}</div>
              </div>
              <div class="user_inp" style="visibility: hidden">
                <div style="width: 120px; color: #afafaf">患者头像</div>
                <div>张三</div>
              </div>
            </div>
          </div>
        </el-card>
        <div style="height: 2vh"></div>
        <el-card class="box-card">
          <template #header>
            <div class="card-header">
              <span>费用明细</span>
            </div>
          </template>
          <div
            style="
              display: flex;
              align-items: center;
              justify-content: space-between;
              margin-bottom: 20px;
            "
          >
            <el-button
              type="primary"
              @click="add"
              :disabled="outpatientxq.visit_status == 1 ? true : false"
              >新增服务</el-button
            >
            <el-button
              type="success"
              @click="yes"
              :disabled="outpatientxq.visit_status == 1 ? true : false"
              >就诊完成</el-button
            >
          </div>
          <div style="width: 100%">
            <el-table
              ref="multipleTableRef"
              style="width: 100%"
              stripe
              border
              size="large"
              :data="zhangdetailed.slice((currentPage5 - 1) * pageSize5, currentPage5 * pageSize5)"
              v-loading="loadings"
            >
              <el-table-column label="序号" property="id" width="120" align="center" />
              <el-table-column property="name" label="服务名称" width="200" align="center" />
              <el-table-column label="服务类型" property="type" width="140" align="center">
                <template #default="scope">
                  {{ scope.row.type === 1 ? '药品' : scope.row.type === 2 ? '体检' : '挂号费' }}
                </template>
              </el-table-column>
              <el-table-column
                property="price"
                label="单价(元)"
                show-overflow-tooltip
                align="center"
              />
              <el-table-column
                property="number"
                label="规格"
                show-overflow-tooltip
                align="center"
              />
              <el-table-column
                property="money"
                label="小计(元)"
                show-overflow-tooltip
                align="center"
              />
              <el-table-column label="订单状态" show-overflow-tooltip align="center">
                <template #default="scope">
                  <span v-if="scope.row.status === 1" style="color: rgb(43, 207, 43)"
                    ><el-tag class="ml-2" type="success">已支付</el-tag></span
                  >
                  <span v-else-if="scope.row.status === 2" style="color: red"
                    ><el-tag class="ml-2" type="danger">未支付</el-tag></span
                  >
                </template>
              </el-table-column>
              <el-table-column label="操作" width="150" align="center">
                <template #default="scope">
                  <div style="display: flex; align-items: center; justify-content: center">
                    <!-- <el-button
                      type="primary"
                      plain
                      size="small"
                      @click="centerDialogVisible(scope.row.id, scope.row)"
                      >编辑</el-button
                    > -->
                    <el-button type="danger" plain size="small" @click="clocks(scope.row.id)"
                      >删除</el-button
                    >
                  </div>
                </template>
              </el-table-column>
            </el-table>
            <div style="height: 1vh"></div>
            <div style="display: flex; justify-content: center">
              <el-pagination
                v-model:current-page="currentPage5"
                v-model:page-size="pageSize5"
                :page-sizes="[10, 20, 50, 100]"
                :small="small"
                :disabled="disabled"
                :background="background"
                layout="total, sizes, prev, pager, next, jumper"
                :total="zhangdetailed.length"
              />
            </div>
          </div>
        </el-card>
        <!-- <div style="height: 2vh;"></div> -->
        <!-- <el-card class="box-card">
          <template #header>
            <div class="card-header">
              <span>订单信息</span>
            </div>
          </template>
          <div>
            <div class="arrow">
              <div class="user_inp">
                <div style="width: 120px;color:#afafaf;">订单总额</div>
                <div>{{ rowsed.money }}&nbsp;(单位：元)</div>
              </div>
              <div class="user_inp">
                <div style="width: 120px;color:#afafaf;">支付方式</div>
                <div>微信支付</div>
              </div>
              <div class="user_inp">
                <div style="width: 120px;color:#afafaf;">支付时间</div>
                <div>{{ rowsed.yes_time }}</div>
              </div>
            </div>
            <div class="arrow">
              <div class="user_inp">
                <div style="width: 120px;color:#afafaf;">订单状态</div>
                <div v-if="rowsed.status === 1" style="color: rgb(43, 207, 43);"><el-tag class="ml-2"
                    type="success">已支付</el-tag></div>
                <div v-else-if="rowsed.status === 2" style="color: red;"><el-tag class="ml-2" type="danger">未支付</el-tag>
                </div>
              </div>
              <div class="user_inp">
                <div style="width: 120px;color:#afafaf;">订单编号</div>
                <div>{{ rowsed.order_code }}</div>
              </div>
              <div class="user_inp" style="visibility: hidden;">
                <div style="width: 120px;color:#afafaf;">患者头像</div>
                <div>张三</div>
              </div>
            </div>
          </div>
        </el-card> -->
        <el-dialog
          v-model="discharge_status"
          title="上传体检结果和图片"
          :close-on-press-escape="false"
          :close-on-click-modal="false"
          :show-close="false"
        >
          <el-form
            ref="results"
            :model="result_data"
            :rules="result"
            label-width="80px"
            class="demo-ruleForm"
            :size="formSize"
            status-icon
          >
            <div v-for="(item, index) in zhangdetailed" :key="index" :title="item.name">
              <el-form-item :label="item.name" :prop="'result' + index" v-if="item.type == 2">
                <el-input v-model="result_data['result' + index]" placeholder="体检结果" />
              </el-form-item>
              <el-form-item :prop="'img' + index" v-if="item.type == 2">
                <el-upload
                  class="avatar-uploader"
                  action="https://lxt.jingyi.icu/pc/Fileimg/file"
                  :show-file-list="false"
                  :on-success="handleAvatarSucces"
                  :before-upload="beforeAvatarUpload"
                >
                  <img
                    @click="setindex(index)"
                    v-if="result_data['img' + index]"
                    :src="url + result_data['img' + index]"
                    class="avatar"
                  />
                  <el-icon @click="setindex(index)" v-else class="avatar-uploader-icon">
                    <Plus />
                  </el-icon>
                </el-upload>
              </el-form-item>
            </div>
            <div style="direction: rtl">
              <el-form-item>
                <el-button type="primary" @click="result_submitForm(results)"> 确认 </el-button>
                <div style="height: 10px; width: 10px"></div>
                <el-button @click="result_resetForm(results)">取消</el-button>
              </el-form-item>
            </div>
          </el-form>
        </el-dialog>
      </div>
      <div style="height: 2vh"></div>
      <el-dialog
        v-model="centerDialogVisibles"
        :title="title"
        width="40%"
        align-center
        :close-on-press-escape="false"
        :close-on-click-modal="false"
        :show-close="false"
      >
        <div>
          <el-form
            ref="ruleFormRef"
            :model="ruleForm"
            :rules="rules"
            label-width="80px"
            class="demo-ruleForm"
            :size="formSize"
            status-icon
          >
            <el-form-item label="服务类型" prop="name">
              <el-select v-model="ruleForm.name" placeholder="请选择服务类型" @change="types">
                <el-option label="体检" value="2" />
                <el-option label="药品" value="1" />
              </el-select>
            </el-form-item>
            <el-form-item label="服务名称" prop="region">
              <el-select
                v-model="ruleForm.region"
                placeholder="请选择服务名称"
                @change="fw_name"
                :disabled="disableds"
              >
                <el-option
                  v-for="item in drugLists"
                  :key="item.id"
                  :label="item.name"
                  :value="item.id"
                />
              </el-select>
            </el-form-item>
            <el-form-item label="规格" prop="count">
              <el-input
                v-model="ruleForm.count"
                placeholder="请输入规格"
                @input="guig(ruleForm.count)"
              />
            </el-form-item>
            <el-form-item label="单价" prop="">
              <el-input :value="prices_name" placeholder="选择服务名称后自动填充" readonly />
            </el-form-item>
            <el-form-item label="总计" prop="" v-if="inp_zj">
              <el-input :value="prices_all" placeholder="选择服务名称后自动填充" readonly />
            </el-form-item>
            <!-- <el-form-item label="支付状态" prop="date1">
              <el-select v-model="ruleForm.date1" placeholder="请选择支付状态">
                <el-option label="已支付" value="1" />
                <el-option label="未支付" value="2" />
              </el-select>
            </el-form-item> -->
            <div style="direction: rtl">
              <el-form-item>
                <el-button type="primary" @click="submitForm(ruleFormRef)"> 确认 </el-button>
                <div style="height: 10px; width: 10px"></div>
                <el-button @click="resetForm(ruleFormRef)">取消</el-button>
              </el-form-item>
            </div>
          </el-form>
        </div>
      </el-dialog>
    </router-view>
  </div>
</template>
<script setup>
  import { ref } from 'vue';
  import { Search, ArrowLeftBold, RefreshRight, Plus } from '@element-plus/icons-vue';
  import {
    Outpatientpayment,
    Outpatientxq,
    ZDdetailed,
    Drug,
    Tlmin,
    Closed,
    Tlist,
    pay_edit,
  } from '@/api/user';
  import { depart } from '@/api/departMents';
  import table2excel from 'js-table2excel';
  import {
    room_list,
    Settlement_list,
    Settlement_del,
    Settlement_add,
    room_add,
    discharge_edit,
  } from '@/api/hospital';
  import { visit, check_list, check_add, visit_detail } from '@/api/visit';
  const multipleTableRef = ref();
  const url = ref('http://lxt.jingyi.icu');
  const value1 = ref('');
  const value = ref('');
  const inp_zj = ref(false);
  const input = ref('');
  const huanz = ref('');
  const tableData = ref([]);
  const results = ref('');
  const currentPage4 = ref(1);
  const pageSize4 = ref(10);
  const currentPage5 = ref(1);
  const pageSize5 = ref(10);
  const options = ref([]);
  const formattedDates = ref([]);
  const datesearch = ref([]);
  const stated = ref(true);
  const defaults = ref(false);
  const zhangdetailed = ref([]);
  const outpatientxq = ref('');
  const title = ref('');
  const disableds = ref(true);
  const centerDialogVisibles = ref(false);
  // const showPreview = ref(false)
  const rowsed = ref('');

  const formSize = ref('default');
  // 调试
  // const stated = ref(false)
  // const defaults = ref(true)
  const loading = ref(true);
  const loadings = ref(false);
  const prices_name = ref('');
  const prices_all = ref('');
  const zong = ref('');
  const zangxid = ref('');
  const use_fy = ref('');
  const bianvalue = ref('');
  const ruleFormRef = ref('');
  const dates = ref('');
  const result_data = ref({});
  const discharge_status = ref(false);
  const index_img = ref(); //上传图片的下标
  const number = ref(); //需要上传体检结果的数量
  const beforeAvatarUpload = (rawFile) => {
    if (rawFile.size / 1024 / 1024 > 2) {
      ElMessage.error('大小不能超过2MB');
      return false;
    }
    return true;
  };
  const handleAvatarSucces = (response, uploadFile) => {
    result_data.value['img' + index_img.value] = response.data.url;
  };
  const setindex = (index) => {
    index_img.value = index;
  };
  const ruleForm = ref({
    name: '',
    region: '',
    count: '',
    // date1: '',
  });
  const result = ref({});

  const result_resetForm = (foms) => {
    console.log(foms);
    if (!foms) return;
    result.value = [];
    setTimeout(() => {
      foms.resetFields();
    }, 10);
    discharge_status.value = false;
  };
  const result_submitForm = async (foms) => {
    console.log(foms);
    if (!foms) return;
    await foms.validate((valid, fields) => {
        if (valid) {
          ElMessageBox.confirm('是否确认就诊完成?', '就诊完成', {
      confirmButtonText: '已就诊完成',
      cancelButtonText: '我再想想',
      type: 'warning',
    })
      .then(() => {
        let array = [];
        for (let i = 0; i < number.value.length; i++) {
          array.push({
            result: result_data.value['result' + (i + 1)],
            img: result_data.value['img' + (i + 1)],
            name: number.value[i],
          });
        }
        discharge_status.value = false;
        setTimeout(() => {
          foms.clearValidate();
        }, 20);
        pay_edit({
          id: outpatientxq.value.id,
          yuyue_id: outpatientxq.value.yuyue_id,
          visit_status: 1,
          arr: JSON.stringify(array),
        })
          .then((res) => {
            if (res.code == 1) {
              ElMessage({
                message: '更新成功',
                type: 'success',
              });
              setTimeout(() => {
                defaults.value = false;
                stated.value = true;
                payment();
              }, 1200);
            } else {
              ElMessage({
                message: '更新失败',
                type: 'success',
              });
            }
          })
          .catch((res) => {
            ElMessage({
              type: 'error',
              message: res.msg,
            });
          });
      })
      .catch(() => {
        ElMessage({
          type: 'info',
          message: '未出院',
        });
      });
        }else{
          console.log('error submit!', fields);
        }
      })
  };
  const drugLists = ref([]);
  const column = [
    {
      title: '序号',
      key: 'id',
      type: 'text',
    },
    {
      title: '患者姓名',
      key: 'user.nickname',
      type: 'text',
    },
    {
      title: '就诊卡号',
      key: 'card',
      type: 'text',
    },
    {
      title: '手机号',
      key: 'user.tel',
      type: 'text',
    },
    {
      title: '挂号科室',
      key: 'depart.name',
      type: 'text',
    },
    {
      title: '医生名称',
      key: 'doctor_name',
      type: 'text',
    },
    {
      title: '支付金额',
      key: 'money',
      type: 'text',
    },
    {
      title: '缴费状态',
      key: 'status',
      type: 'text',
    },
    {
      title: '订单号',
      key: 'order_code',
      type: 'text',
    },
    {
      title: '缴费时间',
      key: 'yes_time',
      type: 'text',
    },
    {
      title: '创建时间',
      key: 'create_time',
      type: 'text',
    },
  ];
  const yes = () => {
    let array = [];
    for (let i in zhangdetailed.value) {
      if (zhangdetailed.value[i].type == 2) {
        array.push(zhangdetailed.value[i].name);
        result.value['result' + i] = [
          {
            required: true,
            message: '请输入体检结果',
            trigger: 'change',
          },
        ];
        result_data.value['result' + i] = '';
        result_data.value['img' + i] = '';
        result_data.value['name'] = zhangdetailed.value[i].name;
        result.value['img' + i] = [
          {
            required: true,
            message: '请上传图片',
            trigger: 'change',
          },
        ];
      }
    }
    if (array.length == 0) {
      ElMessageBox.confirm('是否确认完成就诊?一但完成后不可进行操作', '完成就诊', {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning',
      })
        .then(() => {
          pay_edit({
            id: outpatientxq.value.id,
            yuyue_id: outpatientxq.value.yuyue_id,
            visit_status: 1,
          }).then((res) => {
            if (res.code == 1) {
              ElMessage({
                message: '更新成功',
                type: 'success',
              });
              setTimeout(() => {
                defaults.value = false;
                stated.value = true;
                payment();
              }, 1200);
            } else {
              ElMessage({
                message: '更新失败',
                type: 'success',
              });
            }
          });
        })
        .catch(() => {
          ElMessage({
            type: 'info',
            message: '您点击了取消',
          });
        });
      return;
    }
    number.value = array;
    setTimeout(() => {
      discharge_status.value = true;
    }, 20);
  };
  payment();
  function payment() {
    Outpatientpayment()
      .then((res) => {
        console.log(res);
        tableData.value = res.data;
        datesearch.value = res.data;
        loading.value = false;
      })
      .catch((res) => {
        tableData.value = [];
        datesearch.value = [];
        loading.value = false;
      });
  }
  departs();
  function departs() {
    depart().then((res) => {
      console.log(res);
      for (const dataItem of res.data) {
        options.value.push({ value: dataItem.id, label: dataItem.name });
      }
    });
  }
  function sarend() {
    formattedDates.value = [];
    if (formattedDates.value.length == 0) {
      tableData.value = datesearch.value;
    }
    value1.value.forEach((date) => {
      let inputDate = new Date(date);
      let year = inputDate.getFullYear();
      let month = inputDate.getMonth() + 1; // 月份从 0 开始，需要加 1
      let day = inputDate.getDate();
      let formattedDate =
        year + '-' + (month < 10 ? '0' + month : month) + '-' + (day < 10 ? '0' + day : day);
      formattedDates.value.push(formattedDate);
    });
    let startTimestamp = new Date(formattedDates.value[0]).getTime(); // 获取formattedDates数组的第一个日期的时间戳
    let endTimestamp = new Date(formattedDates.value[1]).getTime(); // 获取formattedDates数组的第二个日期的时间戳
    let result = tableData.value.filter((item) => {
      let itemTimestamp = new Date(item.yes_time).getTime(); // 将yes_time字段转化为时间戳
      console.log(itemTimestamp, startTimestamp, endTimestamp);
      return itemTimestamp >= startTimestamp && itemTimestamp <= endTimestamp; // 判断时间戳是否在范围内
    });
    console.log(result, '日期区间');
    tableData.value = result; // 将符合条件的数据赋值给tableData.value
    console.log(formattedDates.value);
    console.log(datesearch.value, '23456');
  }
  function kssearch(e) {
    dates.value = e;
    const matchingOption = options.value.find((option) => option.value === e);
    console.log(matchingOption, '搜索科室');
    let tableks = [];

    if (matchingOption) {
      value.value = matchingOption.label;
      console.log(value.value, '科室');

      // 使用Array.prototype.filter来找到所有符合条件的值
      const matchingDeparts = datesearch.value.filter(
        (depart) => value.value === depart.depart.name
      );
      tableks.push(...matchingDeparts); // 将所有匹配的值添加到tableks数组中

      console.log(matchingDeparts, '筛选数据');

      if (matchingDeparts.length > 0) {
        tableData.value = tableks;
      } else {
        tableData.value = [];
      }
    } else {
      // 如果没有匹配的选项，将value.value重置为空
      value.value = '';
      tableData.value = []; // 也可以选择清空tableData.value
    }
    if (e == '' || e == undefined) {
      tableData.value = datesearch.value;
    }

    console.log(datesearch.value);
  }

  function docsearch() {
    console.log(input.value);
    let doctor = [];
    if (input.value != '' || input.value != undefined) {
      const doctorData = datesearch.value.filter((depart) =>
        depart.doctor_name.includes(input.value)
      );
      console.log(doctorData);
      doctor.push(...doctorData);
      tableData.value = doctor;
    } else {
      tableData.value = datesearch.value;
    }
  }
  function hzsearch() {
    console.log(huanz.value);
    let doctor = [];
    if (huanz.value != '' || huanz.value != undefined) {
      const doctorData = datesearch.value.filter((depart) =>
        depart.user.nickname.includes(huanz.value)
      );
      console.log(doctorData);
      doctor.push(...doctorData);
      tableData.value = doctor;
    } else {
      tableData.value = datesearch.value;
    }
  }
  const choice = ref([]);
  // 多选
  const handleSelectionChange = (val) => {
    console.log(val);
    choice.value = val;
  };

  function exportExcel() {
    let date_choie = [];
    if (choice.value.length == 0) {
      console.log(123);
      date_choie = tableData.value;
    } else {
      console.log(3333);
      date_choie = choice.value;
    }
    const newData = date_choie.map((item) => ({
      ...item,
      'user.tel': item.user.tel,
      'depart.name': item.depart.name,
      'user.nickname': item.user.nickname,
      'status': item.status == 1 ? '已支付' : '未支付',
      'visit_status': item.visit_status == 1 ? '就诊完成' : '就诊中',
      // 'type': '微信支付'
    }));
    const currentDate = new Date();
    const year = currentDate.getFullYear();
    const month = String(currentDate.getMonth() + 1).padStart(2, '0');
    const day = String(currentDate.getDate()).padStart(2, '0');
    const hours = String(currentDate.getHours()).padStart(2, '0');
    const minutes = String(currentDate.getMinutes()).padStart(2, '0');
    const seconds = String(currentDate.getSeconds()).padStart(2, '0');

    const formattedDate = `${year}-${month}-${day}  ${hours}:${minutes}:${seconds}`;

    const fileName = `门诊缴费记录_${formattedDate}.xlsx`; // 在文件名中附带当前时间的年月日时分秒
    table2excel(column, newData, fileName); // 导出excel
  }
  function targets(id, rows) {
    console.log(id);
    stated.value = false;
    use_fy.value = id;
    defaults.value = true;
    rowsed.value = rows;
    Outpatientxq({
      id: id,
    }).then((res) => {
      console.log(res, '详情');
      if (res.code == 1) {
        outpatientxq.value = res.data;
      } else {
        outpatientxq.value = [];
      }
    });
    if (id != '' || id != undefined) {
      zhang();
    }
  }
  function zhang() {
    ZDdetailed({
      pay_id: use_fy.value,
    }).then((res) => {
      console.log(res, '账单');
      setTimeout(() => {
        loadings.value = false;
        zhangdetailed.value = res.data;
      }, 500);
    });
  }

  function returned() {
    stated.value = true;
    defaults.value = false;
    loadings.value = false;
    zhangdetailed.value = [];
    payment();
  }
  // 预览
  // function previewImage() {
  //   showPreview.value = true;
  // }
  // function closePreview() {
  //   showPreview.value = false;
  // }
  function drap() {
    Drug().then((res) => {
      console.log(res, '药品');
      const drugList = res.data.map((drug) => {
        return { name: drug.name, id: drug.id, price: drug.price };
      });
      console.log(drugList, '重组后的数组');
      drugLists.value = drugList;
      if (drugLists.value || drugLists.value.length == 0) {
        fw_name(ruleForm.value.region);
      }
    });
  }
  function centerDialogVisible(mxid, mxdata) {
    title.value = '编辑';
    centerDialogVisibles.value = true;
    zangxid.value = mxid;
    console.log(mxdata, '编辑回显');
    console.log(drugLists, '编辑服务名称');
    console.log(mxdata.name_id, '服务名称id');
    ruleForm.value.region = parseInt(mxdata.name_id);
    prices_name.value = mxdata.price;
    if (bianvalue.value != '' || bianvalue.value != undefined) {
      prices_all.value = bianvalue.value * prices_name.value;
    }
    ruleForm.value.name = `${mxdata.type}`;

    if (ruleForm.value.name == 1) {
      drap();
      ruleForm.value.count = mxdata.number;

      disableds.value = false;
    } else {
      tix();
      disableds.value = false;
      ruleForm.value.count = mxdata.number;
    }

    // prices_all.value = mxdata.money

    ruleForm.value.date1 = `${mxdata.status}`;
    inp_zj.value = true;
  }

  function clears() {
    centerDialogVisibles.value = false;
  }

  function tix() {
    Tlist().then((res) => {
      console.log(res, '药品');
      const drugList = res.data.map((drug) => {
        return { name: drug.name, id: drug.id, price: drug.price };
      });
      console.log(drugList, '重组后的数组');
      drugLists.value = drugList;
      if (drugLists.value || drugLists.value.length == 0) {
        fw_name(ruleForm.value.region);
      }
    });
  }

  function types(e) {
    console.log(e, '测试');
    if (e == 1) {
      disableds.value = false;
      drap();
    } else {
      tix();
      disableds.value = false;
    }
  }
  const rules = {
    name: [
      {
        required: true,
        message: '请选择服务类型',
        trigger: 'change',
      },
    ],
    region: [
      {
        required: true,
        message: '请选择服务名称',
        trigger: 'change',
      },
    ],
    count: [
      {
        required: true,
        message: '请输入规格',
        trigger: 'change',
      },
    ],
  };

  const submitForm = async (formEl) => {
    if (!formEl) return;
    await formEl.validate((valid, fields) => {
      if (valid) {
        console.log('submit!', ruleForm);
        console.log(ruleForm.value.name);
        console.log(zangxid.value, '门诊缴费记录id');
        console.log(prices_all.value, '总计');
        console.log(prices_name.value, '小计');
        Tlmin({
          pay_id: use_fy.value,
          name_id: ruleForm.value.region,
          price: prices_name.value,
          money: prices_all.value,
          number: ruleForm.value.count,
          type: ruleForm.value.name,
          status: ruleForm.value.date1,
          id: zangxid.value || '',
        }).then((res) => {
          console.log(res);
          if (res.code == 1) {
            ElMessage({
              message: `${res.msg}`,
              type: 'success',
            });
            zhang();
            centerDialogVisibles.value = false;
            ruleForm.value = {
              name: '',
              region: '',
              count: '',
              date1: '',
            };
            setTimeout(() => {
              formEl.clearValidate();
            }, 10);
          } else {
            ElMessage({
              message: `${res.msg}`,
              type: 'error',
            });
          }
        });
      } else {
        console.log('error submit!', fields);
      }
    });
  };

  const resetForm = (formEl) => {
    if (!formEl) return;
    prices_name.value = '';
    inp_zj.value = false;
    ruleForm.value = {
      name: '',
      region: '',
      count: '',
      date1: '',
    };
    setTimeout(() => {
      formEl.clearValidate();
    }, 10);
    centerDialogVisibles.value = false;
  };
  function fw_name(e) {
    console.log(e, '单价ID');
    console.log(ruleForm.value.count, '数量');
    const prices = drugLists.value.filter((drug) => drug.id == e).map((drug) => drug.price);
    // console.log(prices[0], '单价');
    prices_name.value = prices[0];
    if (ruleForm.value.count != '') {
      prices_all.value = prices_name.value * ruleForm.value.count;
    } else {
      prices_all.value = prices_name.value;
      ruleForm.value.count = 1;
    }
    zong.value = prices_name.value;
    console.log(prices[0], '单价');
    if (prices_name.value == '' || prices_name.value == undefined) {
      inp_zj.value = false;
      ruleForm.value.count = '';
    } else {
      if (e != '' || e != undefined) {
        ruleForm.value.count = ruleForm.value.count;
      } else {
        ruleForm.value.count = 1;
      }
      inp_zj.value = true;
      // ruleForm.value.count = 1
    }
  }
  function guig(e) {
    console.log(e);
    bianvalue.value = e;
    prices_all.value = e * zong.value;
  }

  function add() {
    title.value = '添加';
    centerDialogVisibles.value = true;
    prices_all.value = '';
    prices_name.value = '';
    disableds.value = true;
  }

  // function clocks(delid){

  // }
  function clocks(delid) {
    ElMessageBox.confirm('是否确认删除?', '删除科室', {
      confirmButtonText: '确认',
      cancelButtonText: '取消',
      type: 'warning',
    })
      .then(() => {
        Closed({
          id: delid,
        }).then((res) => {
          console.log(res);
          if (res.code == 1) {
            ElMessage({
              type: 'success',
              message: '删除成功',
            });
            zhang();
          } else {
            ElMessage({
              type: 'error',
              message: '删除失败',
            });
          }
        });
      })
      .catch(() => {
        ElMessage({
          type: 'info',
          message: '取消删除',
        });
      });
  }
</script>
<style scoped lang="scss">
  .top_navigate {
    display: flex;
    align-items: center;
  }

  .block {
    display: flex;
    align-items: center;
  }

  //上传
  .avatar-uploader {
    border: 1px dashed var(--el-border-color) !important;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    display: flex;
    align-items: center;
    overflow: hidden;
    transition: var(--el-transition-duration-fast);
  }

  .avatar-uploader .el-upload:hover {
    border-color: var(--el-color-primary);
  }

  .el-icon.avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    text-align: center;
  }

  //上传
  .form_word {
    margin-right: 20px;
  }

  .avatar-uploader .avatar {
    width: 178px;
    height: 178px;
    display: block;
  }

  .blue_ycy {
    width: 32px;
    height: 8px;
    background-color: #006eff;
    border-radius: 20px;
    margin-right: 10px;
  }

  .font_size {
    font-size: 20px;
  }

  .m-2 {
    width: 120px;
  }

  .card-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    color: #006eff;
  }

  .text {
    font-size: 14px;
  }

  .item {
    margin-bottom: 18px;
  }

  .box-card {
    width: 100%;
  }

  .user_inp {
    width: 33.33%;
    display: flex;
    align-items: center;
  }

  .arrow {
    width: 96%;
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-left: 3%;
    height: 7vh;
  }

  /* 预览 */
  /* .preview-container {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background: rgba(0, 0, 0, 0.8);
  display: flex;
  justify-content: center;
  align-items: center;
  z-index: 1000;
}

.preview-image {
  max-width: 80%;
  max-height: 100%;
} */
</style>
